import { Outlet, useLocation, Navigate } from "react-router-dom";
import { routes } from "../router";
import { LocalStorageService } from "../utils/storage";
import { getCatchRouteMeta } from "../utils/router";
import userLayoutLoader from '@/router/LayoutLoader';

const AuthRouter: React.FC = () => {
  const { pathname } = useLocation();
  const token = LocalStorageService.get("token");
  const { permissions } = userLayoutLoader();

  const curRouteMeta = getCatchRouteMeta(pathname, routes[0].children)

  if (token) {
    if (pathname === "/403" || pathname === "/404") return <Outlet />;
    if (pathname === "/login") return <Navigate to="/" replace />;
    if (curRouteMeta?.auth) {
      if (typeof curRouteMeta.auth === 'string' && !permissions.includes(curRouteMeta.auth))
        return <Navigate to="/403" replace />
      else if (Array.isArray(curRouteMeta.auth) && !curRouteMeta.auth.some(v => permissions.includes(v)))
        return <Navigate to="/403" replace />
      else
        return <Outlet />
    }
    return <Outlet />
  } else {
    if (curRouteMeta?.isWhite) {
      return <Outlet />;
    } else {
      return <Navigate to="/login" replace />
    }
  }
};
export default AuthRouter;
